#!/bin/bash
set -e

# 文件列表
files=(
    "/usr/share/bochs/keymaps/x11-pc-us.map"
    "/usr/share/vgabios/vgabios.bin"
    "/usr/share/bochs/BIOS-bochs-latest"
    "./img/hd60M.img"
    "./bochsrc"
)

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

for file in "${files[@]}"; do
    if [ -f "$file" ]; then
        echo -e "${GREEN}✔ 文件存在: $file${NC}"
    else
        echo -e "${RED}❌ 文件不存在: $file${NC}"
    fi
done

# 清理上一次运行，命令拼写修正为 pkill
pkill -9 bochs &> /dev/null || true
pkill -9 xzoom &> /dev/null || true

# 清空磁盘锁定文件
if [ $(find ./ -type f -name "*.lock" | wc -l) -eq 0 ]; then
    echo -e "${GREEN}✔ 磁盘未被锁定${NC}"
else
    echo -e "${RED}❌ 磁盘锁定正在清理...${NC}"
    find ./ -type f -name "*.lock" -exec rm -f {} +
fi

# 1. 清空磁盘前512字节
dd if=/dev/zero of=./img/hd60M.img bs=512 count=1 conv=notrunc > /dev/null 2>&1
echo -e "${GREEN}✔ 磁盘MRB清空${NC}"

# 2. 编译mbr，并写入磁盘
nasm -o ./code/mbr.bin ./code/mbr.S -l ./code/mbr.lst
echo -e "${GREEN}✔ 编译完毕${NC}"
dd if=./code/mbr.bin of=./img/hd60M.img bs=512 count=1 conv=notrunc > /dev/null 2>&1
echo -e "${GREEN}✔ 磁盘MRB写入${NC}"

# 3. 检查mbr.bin是否存在
if [ -f ./code/mbr.bin ]; then
    echo -e "${GREEN}✔ ./code/mbr.bin 存在${NC}"
else
    echo -e "${RED}❌ ./code/mbr.bin 不存在${NC}"
    exit 1
fi

# 4. 检查磁盘前512字节最后两字节是否为55AA
last2=$(xxd -p -l 2 -s 510 ./img/hd60M.img)
if [[ "$last2" == "55aa" || "$last2" == "55AA" ]]; then
    echo -e "${GREEN}✔ 镜像前512字节结尾为55AA${NC}"
else
    echo -e "${RED}❌ 镜像前512字节结尾不是55AA，而是: $last2${NC}"
fi

sleep 1
echo "正在启动bochs"
nohup bochs -qf ./bochsrc > bochs_run.log 2>&1 &
echo "正在放大镜"
nohup xzoom -geometry 1700x1260 > xzoom_run.log 2>&1 &